/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cratos.xxgramoss.message;

import com.cratos.xxgram.platf.base.BaseService;
import com.cratos.xxgram.platf.message.BasicContent;
import com.cratos.xxgram.platf.message.MessageRecordHis;
import com.cratos.xxgramoss.base.RetCodes;
import static com.cratos.xxgramoss.base.RetCodes.RET_USER_NOTEXISTS;
import javax.annotation.Resource;
import org.redkale.net.http.RestService;
import org.redkale.source.*;
import static com.cratos.xxgramoss.base.Services.*;
import com.cratos.xxgramoss.user.UserOssService;
import java.util.HashSet;
import java.util.Map;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;
import org.redkale.util.Sheet;

/**
 *
 * @author alter
 */
@RestService(comment = "单聊消息", moduleid = MODULE_CHATRECORD)
public class MessageOssService extends BaseService {

    @Resource(name = "platf")
    protected DataSource platfSource;

    @Resource
    protected UserOssService userService;

    @RestMapping(auth = true, actionid = ACTION_QUERY, comment = "单聊消息")
    public RetResult<Sheet<MessageRecordHis>> queryMessageRecordList(MessageRecordHisBean bean, Flipper flipper) {
        bean.setMsgkind(MessageRecordHis.MSG_KIND_PRIVATE);
        bean.setMsgtype(BasicContent.OBJ_IMAGE_MESSAGE);
        Sheet<MessageRecordHis> sheet = platfSource.querySheet(MessageRecordHis.class, flipper, bean);
        final HashSet<Integer> userids = new HashSet<>();
        sheet.forEach(msg -> {
            userids.add(msg.getFromid());
            userids.add(msg.getTargetid());
        });
        Map<Integer, String> userNames = userService.queryUserNames(userids);
        sheet.forEach(msg -> {
            msg.setFromname(userNames.get(msg.getFromid()));
            msg.setTargetname(userNames.get(msg.getTargetid()));
        });
        return new RetResult<>(sheet);
    }

    @RestMapping(auth = true, actionid = ACTION_UPDATE, comment = "删除聊天记录")
    public RetResult delMessageRecord(String[] messageid) {
        if (messageid == null || messageid.length < 1) {
            return RetCodes.retResult(RetCodes.RET_PARAMS_ILLEGAL);
        }
        if (messageid[0] == null) {
            return null;
        }
        for (String id : messageid) {
            MessageRecordHis msg = platfSource.find(MessageRecordHis.class, id);
            if (msg == null) {
                return RetCodes.retResult(RET_USER_NOTEXISTS);
            }
            platfSource.updateColumn(MessageRecordHis.class, msg.getMessageid(), "del", MessageRecordHis.STATUS_DELTED);
        }
        return RetResult.success();
    }

}
